package com.zzyl;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;

public class BaiduQianfanClient {

    private final RestTemplate restTemplate;
    private final String apiUrl = "https://qianfan.baidubce.com/v2/chat/completions";
    private final String authToken = "Bearer bce-v3/ALTAK-O6wzc4aOObW8RoRO091vW/e2cbd82af14d0527aa6d19b046ac7e05da0dd743";
//    private static final String prompt = "吴亦凡犯了什么罪";


    public BaiduQianfanClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String sendChatRequest( String prompt) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", authToken);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "ernie-lite-8k");

        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(Map.of("role", "system", "content", "吴亦凡犯了什么罪"));
        messages.add(Map.of("role", "user", "content",prompt ));

        requestBody.put("messages", messages);

        // 创建请求实体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(
                apiUrl,
                HttpMethod.POST,
                requestEntity,
                String.class
        );

        System.out.println(response.getBody());
        return response.getBody();

    }
    public static void main(String[] args) {
        // 创建RestTemplate实例
        RestTemplate restTemplate = new RestTemplate();

        // 创建客户端实例
        BaiduQianfanClient client = new BaiduQianfanClient(restTemplate);

        System.out.println("开始调用百度千帆大模型API...");

        try {
//            // 示例1: 发送默认请求
//            System.out.println("=== 示例1: 发送默认请求 ===");
//            String response1 = client.sendChatRequest(prompt);
//            System.out.println("默认请求响应: " + response1);

            // 示例2: 发送自定义消息
            System.out.println("\n=== 示例2: 发送自定义消息 ===");
            String response2 = client.sendChatRequest("请介绍一下你自己");
            System.out.println("自定义消息响应: " + response2);

//            // 示例3: 发送多个消息对话
//            System.out.println("\n=== 示例3: 发送多个消息对话 ===");
//            String response3 = client.sendChatRequest("Java编程有什么优势？");
//            System.out.println("编程问题响应: " + response3);

        } catch (Exception e) {
            System.err.println("调用API时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
